let instance = axios.create()
instance.defaults.baseURL = 'http://localhost:3000'
instance.defaults.headers['Content-Type'] = 'multipart/form-data'
instance.interceptors.response.use(response => {
  return response.data
})

new Vue({
  el: '#app',
  data() {
    return {
      normalFile: null,
      normalPercentage: 0,
      normalUploading: false,
      bigFile: null,
      bigFilePercentage: 0,
      bigFileUploading: false
    }
  },
  methods: {
    handleFileSelect(refName) {
      this.$refs[refName].click()
    },
    handleNormalFileChange(event) {
      this.normalFile = event.target.files[0]
    },
    handleNormalUpload() {
      const data = new FormData()
      data.append('file', this.normalFile)
      this.normalUploading = true
      instance.post('/upload/normal', data, {
        onUploadProgress: (event) => {
          const percentage = Math.round(event.loaded / event.total * 100)
          this.normalPercentage = percentage
        }
      }).then(res => {
        this.$message({
          message: '文件上传成功',
          type: 'success'
        })
        setTimeout(() => {
          this.normalUploading = false
          this.normalPercentage = 0
          this.$refs.normalFileInput = ''
        }, 1000)
      })
    },
    handleBigFileChange (event) {
      this.bigFile = event.target.files[0]
    },
    async handleBigFileUpload () {
      this.bigFileUploading = true
      const { hash, suffix } = await this.getFileHash()
      // 分片
      let max = 1024 * 100
      let count = Math.ceil(this.bigFile.size / max)
      let index = 0
      const chunks = []
      if (count > 100) {
        max = this.bigFile.size / 100
        count = 100
      }
      while (index < count) {
        chunks.push({
        // file文件本身就具有slice方法，见下图
          file: this.bigFile.slice(index * max, (index + 1) * max),
          filename: `${hash}_${index + 1}.${suffix}`
        })
        index++
      }
      const uploadedList = await instance.get('/upload/chunk_already', { params: { hash } })
      const chunkUploadProList = []
      chunks.forEach(chunk => {
        if (uploadedList.length && uploadedList.includes(chunk.filename)) return
        const data = new FormData()
        data.append('hash', hash)
        data.append('file', chunk.file, chunk.filename)
        chunkUploadProList.push(instance.post('/upload/chunk', data))
      })
      Promise.all(chunkUploadProList).then(resList => {
        const data = new FormData()
        data.append('hash', hash)
        data.append('count', count)
        instance.post('/upload/merge', data).then(res => {
          this.$message({
            message: '文件上传成功',
            type: 'success'
          })
          setTimeout(() => {
            this.bigFileUploading = false
            this.bigFilePercentage = 0
            this.$refs.BigFileInput = ''
          }, 1000)
        })
      })
    },
    getFileHash () {
      return new Promise(resolve => {
        const fileReader = new FileReader()
        fileReader.readAsArrayBuffer(this.bigFile)
        fileReader.onload = event => {
          const buffer = event.target.result
          const spark = new SparkMD5.ArrayBuffer()
          let hash = null
          const suffix = /\.([a-zA-Z0-9]+)$/.exec(this.bigFile.name)[1]
          spark.append(buffer)
          hash = spark.end()
          resolve({
            hash,
            suffix
          })
        }
      })
    }
  }
})